// pages/goodsDetail/goodsDetail.js
var app=getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
      goodsInfo:null,
      autoplay:true,
      interval:3000,
      rateList:[],
      reList1:[],
      show: false,
      poptype: 1,
      count: 1,//加入购物车数量
      showbuyBox: false,
      selectedAttrs: [],
      selectedImg: '',
      skuId: '',//添加购物车规格id
      skulist: [],//规格
      parameters: [],//参数
      selectedprice:0,//选中的价格
      imgPath:app.globalData.imgPath,
      showMoreRate: false,
      ratecount: 0,
      scrollid:'section1',
      showmenuItem: false,
      winHeight:0,
      top1:0,
      top2:0,
      top3:0,
      top4:0,
      scrollTop: 0,
      tabon:1,
      poptype2: 1,//产品参数规格
     showsku:false,
     showparams:false,
     skuInfo:null,//选中的产品规格详情
    introHeight:0,//详情的高度
    tabHeight:0,//tab高度
    cancollect:true,//可以点击收藏
    userInfo:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   let userInfo = wx.getStorageSync('userInfo');
   //console.log(userInfo)
    this.setData({ userInfo: userInfo});
    wx.showShareMenu({
      withShareTicket: true,
      success: function (res) {
        // 分享成功
        console.log('shareMenu share success')
        console.log('分享' + JSON.stringify(res))
      },
      fail: function (res) {
        // 分享失败
        console.log(res)
      }
    })
    var query = wx.createSelectorQuery();
      let id=options.id;
    //  let id=378
      let self=this;
    query.select('#tab-con').boundingClientRect(function (res) {
      // console.log(res.top)
      self.setData({ tabHeight:res.height})
    }).exec()
    if (options.cancollect){
      this.setData({ cancollect: options.cancollect});
      }
    query.select('#tab-con').boundingClientRect(function (res) {
      // console.log(res.top)
      self.setData({ tabHeight:res.height})
    }).exec()
      wx.request({//评论
        url:app.globalData.reqPath+'shop/GoodsComments',
        header:{
          'authorization': app.globalData.authorization
        },
        data:{
          productId:id,
        },
        success:function({data}){
            if(data.code==200){
              let list = data.data.list;
              self.setData({ rateList: list.splice(0,3), ratecount: data.data.dataCount})
              setTimeout(function () {
                query.select('#section2').boundingClientRect(function (res) {
                  // console.log(res.top)
                  self.setData({ top2: res.top })
                }).exec()
              },200)
            }
        }
      })
    wx.request({
      url: app.globalData.reqPath + 'shop/GoodsProducts/' + id,
      header: {
        'authorization': app.globalData.authorization
      },
      success: function ({ data }) {
        if (data.code == 200) {
          let info = data.data;
          for (var i in info.attrItems) {
            for (var j in info.attrItems[i].values) {
              info.attrItems[i].values[j].selected = false;
            }
          }
          let skulist = info.attrItems.filter(function (item) {
            return item.isSku
          })
          // console.log(skulist)
          let parameters = info.attrItems;
          self.setData({ goodsInfo: info, selectedImg: info.imgPath, skulist: skulist, parameters: parameters, selectedprice: info.vipPrice })
          setTimeout(function () {
            let introHeight;
            query.select('#section3').boundingClientRect(function (res) {
               //console.log("高度"+res.height)
              introHeight=res.height
              self.setData({ top3: res.top, introHeight:res.height,top4:res.top+introHeight});
              //console.log("top4:"+self.data.top4)
            }).exec(function(){

            })
          }, 600)
        }
      }
    })



    wx.request({
      url: app.globalData.reqPath + 'shop/GoodsProducts/' + id,
      header: {
        'authorization': app.globalData.authorization
      },
      success: function ({ data }) {
        if (data.code == 200) {
          let info = data.data;
          for (var i in info.attrItems) {
            for (var j in info.attrItems[i].values) {
              info.attrItems[i].values[j].selected = false;
            }
          }
          let skulist=[]
          if (info.attrItems){
            skulist = info.attrItems.filter(function (item) {
              return item.isSku
            })
          }

          // console.log(skulist)
          let parameters = info.attrItems;

          self.setData({ goodsInfo: info, selectedImg: info.imgPath, skulist: skulist, parameters: parameters, selectedprice: info.vipPrice })
          setTimeout(function () {
            let introHeight;
            query.select('#section3').boundingClientRect(function (res) {
               //console.log("高度"+res.height)
              introHeight=res.height
              self.setData({ top3: res.top, introHeight:res.height,top4:res.top+introHeight});
              //console.log("top4:"+self.data.top4)
            }).exec(function(){

            })
          }, 600)
        }
      }
    })



      wx.request({
        url:app.globalData.reqPath+'shop/GoodsProductsRefer',
        header:{
          'authorization': app.globalData.authorization
        },
        data:{
        
        },
        success:function({data}){
          self.setData({ reList1: data.data })

        }
      })

    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight;
      //  console.log(clientHeight)
        //   clientWidth = res.windowWidth,
        //   rpxR = 750 / clientWidth;
        // var calc = clientHeight * rpxR - 180;
        self.setData({
          winHeight: clientHeight
        });
      }
    });
    
    query.select('#section1').boundingClientRect(function (res) {
     // console.log(res.top)
      self.setData({top1:res.top})  
    }).exec()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  addcollect:function(){
    let self = this;
    if(this.data.cancollect){
    this.setData({cancollect:false})
    wx.request({
      url: app.globalData.reqPath + 'shop/MembersFarvirate',
      header: {
        'authorization': app.globalData.authorization
      },
      data: {
        productId: this.data.goodsInfo.id
      },
      method: 'POST',
      success: function ({ data, header }) {
        if (header.authorization && header.authorization != app.globalData.authorization) {
          app.globalData.authorization = header.authorization;
        }
        if (data.code == 200) {
          wx.showToast({
            title: '收藏成功',
            icon: 'none',
            success:function(){
              self.onLoad({ id: self.data.goodsInfo.id });
            }
          })
          // setTimeout(function () {
          //   self.onLoad({ id:self.data.goodsInfo.id });
          // }, 600)
        }
      }
    })
    }
  },
  canccollect:function(){
    let self = this;

    wx.request({
      url: app.globalData.reqPath + 'shop/MembersFarvirate/' + this.data.goodsInfo.farvirateId,
      method: 'DELETE',
      header: {
        'authorization': app.globalData.authorization
      },
      success: function ({ data, header }) {
        if (header.authorization && header.authorization != app.globalData.authorization) {
          app.globalData.authorization = header.authorization;
        }
        if (data.code == 200) {
          wx.showToast({
            title: '取消成功',
            icon: 'none',
            success: function () {
              self.onLoad({ id: self.data.goodsInfo.id, cancollect: true});
            }
          })
        }
      }
    })
  },
  onClickButton: function (e) {
    //poptype   1加入购物车
    let poptype = e.currentTarget.dataset.poptype;
    this.setData({ show: true, poptype: poptype });
  },
  checkattr: function (e) {//选择尺码规格
    let self = this;
    let pindex = e.currentTarget.dataset.pindex;
    let index = e.currentTarget.dataset.index;
    let info = this.data.goodsInfo;
    let len = info.attrItems.length;
    // let selectedAttrs=[];

    for (var i in info.attrItems) {
      for (var j in info.attrItems[i].values) {
        if (i == pindex && j == index) {
          info.attrItems[i].values[j].selected = true;
          // this.data.selectedAttrs.push(([info.attrItems[i].attributeId, info.attrItems[i].values[j].valueId]))            
        } else if (i == pindex) {
          info.attrItems[i].values[j].selected = false;
        }
      }
    }
    var selectedAttrs = []
    info.attrItems.map(function (item) {
      item.values.map(function (vitem) {
        if (vitem.selected) {
          selectedAttrs.push([item.attributeId, vitem.valueId])
        }
      })
    })
    //  console.log(selectedAttrs)
    this.setData({ goodsInfo: info })
    let pid = e.currentTarget.dataset.attrid;
    let vid = e.currentTarget.dataset.vid
    if (selectedAttrs.length==len){
        wx.request({
          url: app.globalData.reqPath + 'shop/AttrToSku',
          data: {
            skuAttrs: selectedAttrs,
            productId: this.data.goodsInfo.id
          },
          header: {
            'authorization': app.globalData.authorization
          },
          method: 'POST',
          success: function ({ data, header }) {
            if (header.authorization && header.authorization != app.globalData.authorization) {
              app.globalData.authorization = header.authorization;
            }
            // console.log(data)
            if (data.code == 200) {
              self.setData({ selectedImg: data.data.skuImg, skuId: data.data.id, selectedprice: data.data.vipPrice, skuInfo:data.data})
            }
          }
        })    
    }

  }, //show
  onClose:function(){
    this.setData({show:false})
  },
  conaddCar: function () {//确定加入购物车
    let self = this;
    let subType = this.data.poptype;
    if (this.data.skulist.length > 0) {//有规格
      if (this.data.skuId != '') {
        let data = {
          quantity: this.data.count,
          skuId: this.data.skuId
        }
        if (subType == 1) {//加入购物车
          wx.request({
            url: app.globalData.reqPath + 'shop/MembersCart',
            method: 'POST',
            header: {
              'authorization': app.globalData.authorization
            },
            data: data,
            success: function ({ data, header }) {
              if (header.authorization && header.authorization != app.globalData.authorization) {
                app.globalData.authorization = header.authorization;
              }
              if (data.code == 200) {
                wx.showToast({
                  title: '加入成功',
                })
                setTimeout(function () {
                  self.setData({ show: false })
                }, 600)
              }
            }
          })
        } else if (subType == 2) {//立即购买
          wx.setStorageSync('buysingleId', this.data.goodsInfo.id);
          wx.setStorageSync('buysingleskuId', this.data.skuId);
          wx.setStorageSync('buysingleNum', this.data.count);
          wx.setStorageSync('buysingleinfo', this.data.skuInfo);
          wx.navigateTo({
            url: '/pages/suborder/suborder?r=1',
          })
        }
        // console.log(data)
      } else {
        wx.showToast({
          title: '请选择规格',
          icon: 'none'
        })
      }
    } else {//没有规格
      let data = {
        quantity: this.data.count,
        skuId: this.data.goodsInfo.skus[0].id
      }
      if (subType == 1) {//加入购物车

        wx.request({
          url: app.globalData.reqPath + 'shop/MembersCart',
          method: 'POST',
          header: {
            'authorization': app.globalData.authorization
          },
          data: data,
          success: function ({ data, header }) {
            if (header.authorization && header.authorization != app.globalData.authorization) {
              app.globalData.authorization = header.authorization;
            }
            if (data.code == 200) {
              wx.showToast({
                title: '加入成功',
              })
              setTimeout(function () {
                self.setData({ show: false })
              }, 600)
            }
          }
        })
      } else if (subType == 2) {
        wx.setStorageSync('buysingleId', this.data.goodsInfo.id);
        wx.setStorageSync('buysingleskuId', this.data.goodsInfo.skus[0].id);
        wx.setStorageSync('buysingleNum', this.data.count);
        wx.setStorageSync('buysingleprice', this.data.selectedprice);
        wx.setStorageSync('buysingleinfo', this.data.goodsInfo.skus[0]);
        wx.navigateTo({
          url: '/pages/suborder/suborder?r=1',
        })
      }
    }

  },
  onClickbuyButton: function (e) {//立即购买
    let poptype = e.currentTarget.dataset.poptype;
    this.setData({ show: true, poptype: poptype });
  },
  scroll:function(e){
   // console.log(e.detail)
    let scroollT=e.detail.scrollTop;
    let top1=0;
    let top2 = this.data.top2 - this.data.tabHeight;
    let top3 = this.data.top3 - this.data.tabHeight;
    let top4 = this.data.top4 - this.data.tabHeight*2;
    //console.log("gun" + scroollT)
    //console.log(top4)
    if (scroollT<top2){
      this.setData({tabon:1})
    } else if (scroollT>=top2&&scroollT<top3){
      this.setData({ tabon: 2 })
    } else if (scroollT>=top3&&scroollT<top4){
      this.setData({ tabon:3 })
    } else if (scroollT>top4){
      this.setData({tabon:4})
    }

  },
  changeTab:function(e){
    let index=e.currentTarget.dataset.index;
    //console.log(index)
    this.setData({ tabon:index,scrollid:'section'+index})
  },
  addcarnumChange: function (e) {//加入购物车数量步进器
    //console.log(e.detail)
    this.setData({ count: e.detail })
  },
  showMenu:function(){//显示顶部的目录
    let show=this.data.showmenuItem;
    show=!show;
    this.setData({showmenuItem:show})
  },
  closeMenu:function(){//关闭顶部的目录
    this.setData({ showmenuItem: false})
  },
  toblock3:function(){
    this.setData({ scrollTop: this.data.top3 - this.data.tabHeight})
  },
  toblock4:function(){
    //console.log(this.data.top4)
    this.setData({ scrollTop: this.data.top4 - this.data.tabHeight})
  },
  toblock2:function(){
    //console.log(this.data.top2)
    this.setData({ scrollTop: this.data.top2 - this.data.tabHeight})
  },
  toblock1: function () {
   // console.log(this.data.top1)
    this.setData({ scrollTop:0 })
  },
  selecsku:function(){
    this.setData({showsku:true})
  },
  onCloseshowsku:function(){
    this.setData({showsku:false});
  },
  showparams:function(){
    this.setData({showparams:true});
  },
  closeparams:function(){
    this.setData({showparams:false});
  },
  onShareAppMessage: function () {
    return {
      title: '转发',
      path: '/pages/index/index?referPhone='+this.data.userInfo.phone,
      //  path:path,
      success: function (res) {
        console.log(JSON.stringify(res));
      },
      fail: function (res) {
        // 分享失败
        console.log(res)
      }
    }
  },
  
})